import { Sequelize } from 'sequelize';
import { createClient } from 'redis';
import { Client } from 'elasticsearch';
import { config } from '../config';

// MySQL连接
export const sequelize = new Sequelize({
  dialect: config.database.dialect,
  host: config.database.host,
  port: config.database.port,
  username: config.database.username,
  password: config.database.password,
  database: config.database.database,
  logging: config.env === 'development' ? console.log : false,
  define: {
    timestamps: true, // 添加createdAt和updatedAt字段
    paranoid: true, // 软删除，添加deletedAt字段
    underscored: true, // 使用下划线命名法
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci',
  },
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
});

// Redis客户端
export const redisClient = createClient({
  url: `redis://${config.redis.password ? `${config.redis.password}@` : ''}${config.redis.host}:${config.redis.port}`,
});

// Elasticsearch客户端
export const esClient = new Client({
  host: `${config.elasticsearch.host}:${config.elasticsearch.port}`,
});

// 初始化数据库连接
export const setupDatabase = async () => {
  try {
    // 连接MySQL
    await sequelize.authenticate();
    console.log('MySQL连接成功');

    // 同步模型到数据库
    if (config.env === 'development') {
      await sequelize.sync({ alter: true });
      console.log('数据库模型同步成功');
    }

    // 连接Redis
    await redisClient.connect();
    console.log('Redis连接成功');

    // 检查Elasticsearch连接
    await esClient.ping();
    console.log('Elasticsearch连接成功');
  } catch (error) {
    console.error('数据库连接失败:', error);
    throw error;
  }
}; 